#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    this->setWindowTitle("主页");
    db = Database::getInstance().getDatabase();
    server = new QTcpServer(this);
    server->listen(QHostAddress("127.0.0.1"),8888);
    connect(server,&QTcpServer::newConnection,this,&Widget::new_connect);

    userpage = new LogReg;
    log_state = userpage->get_log_flag();
    connect(userpage,&LogReg::show_main,[=](){this->show();});
    man = new manager;
    connect(man,&manager::back,this,&Widget::back);
    survey = new Showsurvey;
    connect(survey,&Showsurvey::show_main,[=](){survey->close();this->show();});
}

Widget::~Widget()
{
    delete ui;
}

void Widget::on_pushButton_manager_clicked()
{
    log_state = userpage->get_log_flag();
    qDebug() << log_state;
    if(!log_state)
    {
        QMessageBox msgBox(this);
        msgBox.setIcon(QMessageBox::Information);
        msgBox.setText("请先登录");
        msgBox.setStandardButtons(QMessageBox::Ok);

        // 连接消息框的 finished 信号到显示 userpage 的槽
        QObject::connect(&msgBox, &QMessageBox::finished, this, [this](){

            userpage->show();
        });

        msgBox.exec(); // 显示消息框
    }
    else
    {
        this->close();
        man->show();

    }
}

void Widget::on_pushButton_search_clicked()
{
    log_state = userpage->get_log_flag();
    if(!log_state)
    {
        QMessageBox msgBox(this);
        msgBox.setIcon(QMessageBox::Information);
        msgBox.setText("请先登录");
        msgBox.setStandardButtons(QMessageBox::Ok);

        // 连接消息框的 finished 信号到显示 userpage 的槽
        QObject::connect(&msgBox, &QMessageBox::finished, this, [this](){

            userpage->show();
            this->hide();
        });

        msgBox.exec(); // 显示消息框
    }
    else
    {
        show_que = new ShowQue;
        this->hide();
        show_que->show();
        connect(show_que,&ShowQue::show_back,this,&Widget::show_back);
    }
}

void Widget::on_pushButton_show_clicked()
{
    log_state = userpage->get_log_flag();
    if(!log_state)
    {
        QMessageBox msgBox(this);
        msgBox.setIcon(QMessageBox::Information);
        msgBox.setText("请先登录");
        msgBox.setStandardButtons(QMessageBox::Ok);

        // 连接消息框的 finished 信号到显示 userpage 的槽
        QObject::connect(&msgBox, &QMessageBox::finished, this, [this](){

            userpage->show();
            this->hide();
        });

        msgBox.exec(); // 显示消息框
    }
    else
    {
        survey->show();
        this->hide();
    }
}

void Widget::on_pushButton_exit_clicked()
{
    server->close();
    this->close();
}

void Widget::show_back()
{
    show_que->close();
    this->show();
}

void Widget::back()
{
    man->close();
    this->show();
}

void Widget::new_connect()
{
    if(server->hasPendingConnections()){
        socket = server->nextPendingConnection();
        qDebug() << "新的客户连接";
        connect(socket,&QTcpSocket::readyRead,this,&Widget::recv_data);
        connect(socket,&QTcpSocket::disconnected,[=](){
            qDebug() << "客户端已断开连接";
        });
    }
}

void Widget::recv_data()
{
    QByteArray data = socket->readAll();
    qDebug() << data;
    QSqlQuery query(db);
    if(data == "question")
    {
        QSqlQuery query(db);
        if (query.exec("SELECT id, text, options FROM questions")) {
            QJsonArray questionsArray;
            while(query.next()) {
                int id = query.value(0).toInt();
                QString text = query.value(1).toString();
                QString optionsStr = query.value(2).toString();
                // 选项是以|分隔的字符串
                QStringList optionsList = optionsStr.split('|');
                QJsonArray optionsArray;
                foreach(const QString &option, optionsList) {
                    optionsArray.append(option);
                }
                QJsonObject questionObj;
                questionObj["id"] = id;
                questionObj["text"] = text;
                questionObj["options"] = optionsArray;

                questionsArray.append(questionObj);
            }
            QJsonDocument doc(questionsArray);
            QByteArray jsonData = doc.toJson();

            // 发送数据给客户端
            socket->write(jsonData);
            socket->flush();
        } else {
            qDebug() << "Database error:" << query.lastError().text();
        }
    }
    else
    {
        QJsonDocument doc = QJsonDocument::fromJson(data);
        if (doc.isObject())
        {
            QJsonObject submitData = doc.object();
            QString clientName = submitData["client_name"].toString();
            QString submitTime = submitData["submit_time"].toString();
            QJsonArray answersArray = submitData["answers"].toArray();
            for (const QJsonValue &answerValue : answersArray)
            {
                if (!answerValue.isObject())
                {
                    qDebug() << "Invalid answer object found";
                    continue;
                }
                QJsonObject answerObj = answerValue.toObject();
                int questionId = answerObj["question_id"].toInt();
                QString answer = answerObj["answer"].toString();

                if (questionId <= 0 || answer.isEmpty())
                {
                    qDebug() << "Invalid question ID or answer found";
                    continue;
                }
                if (!query.exec(QString("INSERT INTO submissions (client_name, submit_time, question_id, answer) VALUES ('%1', '%2', %3, '%4')")
                                .arg(clientName).arg(submitTime).arg(questionId).arg(answer)))
                {
                    qDebug() << "Database error:" << query.lastError().text();
                }
            }

            qDebug() << "Data saved to database!";
        }
        else
        {
            qDebug() << "Invalid JSON data received";
        }
    }

}


void Widget::on_pushButton_clicked()
{
    log_state = userpage->get_log_flag();
    if(log_state)
    {
        QMessageBox::warning(this,"警告","您已经登录过了");
        return;
    }
    else
        userpage->show();
}


